package com.xuhai.blog19.common.shiro;

import com.xuhai.blog19.admin.entity.ExpiresEntity;
import com.xuhai.blog19.admin.entity.UserEntity;
import com.xuhai.blog19.admin.service.ExpiresService;
import com.xuhai.blog19.admin.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2.自定义登录检查
 *
 * @Author PangJunjie
 * @Date 2022/2/9/009
 */
@Component
public class Shiro2Realm extends AuthorizingRealm {

    @Autowired
    private ExpiresService expiresService;

    @Autowired
    private UserService userService;

    /*该方法必须主动重写，否则自定义token无效*/
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Shiro2Token;
    }

    /*验证权限，可以做到按钮级控制*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    /*验证登录*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*获取token*/
        String token = (String) authenticationToken.getPrincipal();
        /*获取token在数据库中的存储信息*/
        ExpiresEntity expires = expiresService.getByToken(token);
        /*判断token是否存在以及是否过期*/
        if (expires == null || expires.getExpires().getTime() < System.currentTimeMillis()) {
            throw new AuthenticationException("token失效");
        }
        /*获取当前登录的用户信息*/
        UserEntity loginUser = userService.getById(expires.getUserId());
        /*存入shiro管理器并放行*/
        return new SimpleAuthenticationInfo(loginUser, token, getName());
    }
}
